package net.lzzy;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class ThredCooperation {
    private static Usr usr = new Usr();

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new Sava_CourierDemo());
        executor.execute(new Take_CourierDemo());
        executor.shutdown();
    }

    public static class Sava_CourierDemo implements Runnable{

        @Override
        public void run() {
            try {
                while (true){
                    usr.Sava_Courier((int) (Math.random()*10+1));
                    Thread.sleep(10000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static class Take_CourierDemo implements Runnable{
        @Override
        public void run() {
            while (true){
                usr.Take_Courier((int) (Math.random()*10+1));
            }
        }
    }


    private static class Usr{
        /*建锁*/
        private static Lock lock = new ReentrantLock();

        /*获取信号*/
        private static Condition newSava_Courier = lock.newCondition();

        private int number;

        public int getNumber() {
            return number;
        }
        /* 取快递*/
        public void Take_Courier(int usr_number){
            lock.lock();
            try {
                while (number<usr_number){
                    newSava_Courier.await();
                }
                number-=usr_number;
                System.out.println("已取出"+usr_number+"个"+"\t你还有"+getNumber()+"个快递没有取");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
        /* 存快递*/
        public void Sava_Courier(int new_number){
            lock.lock();
            try {
                number += new_number;
                System.out.println("存入"+new_number+"个快递\t你有"+getNumber()+"个快递没有取");
                newSava_Courier.signalAll();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }}}





